package com.ftqh.tutorial.exception.handler;

import com.ftqh.tutorial.exception.EntityNotFoundException;
import com.ftqh.tutorial.web.vo.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(EntityNotFoundException.class)
    public Object handleEntityNotFound(EntityNotFoundException e) {
        return ResponseEntity.ok()
                .statusCode(HttpStatus.NOT_FOUND)
                .message(e.getMessage())
                .build();
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public Object handleNoHandlerFound(NoHandlerFoundException e) {
        return handleException(HttpStatus.NOT_FOUND,e);
    }
    @ExceptionHandler({TypeMismatchException.class, MissingServletRequestParameterException.class,
            ServletRequestBindingException.class, HttpMessageNotReadableException.class,
            MethodArgumentNotValidException.class, MissingServletRequestPartException.class, BindException.class})
    public Object handleBadRequest(Exception e) {
        return handleException(HttpStatus.BAD_REQUEST,e);
    }
    @ExceptionHandler({MissingPathVariableException.class, ConversionNotSupportedException.class,
            HttpMessageNotWritableException.class})
    public Object handleInternalServerError(Exception e) {
        return handleException(HttpStatus.INTERNAL_SERVER_ERROR,e);
    }
    private ResponseEntity handleException(HttpStatus statusCode, Exception e){
        logger.error(e.getMessage());  // 记录错误信息
        return ResponseEntity.error()
                .statusCode(statusCode)
                .message(e.getMessage())
                .build();
    }
}
